clear

set graphics off

local loopnum=${masteriter}
local thresh=${masterthresh}
local agegroup "${agegroup}"

set seed  [withheld]

local sample all
local agegroup all
local ltfpvar tfpvar

	quietly use "${data}/data_`agegroup'.dta", clear	
	quietly bys S J: gen cellcount=_N
	keep if cellcount>=`thresh'

	if("`sample'"=="young"){
		keep if age<=5
	}
	if("`sample'"=="old"){
		keep if age>5
	}
		
	quietly cap rename `ltfpvar' lA

	*Groups	
	quietly egen JT		=group(J T)
	quietly egen ST		=group(S T)
	quietly egen SJT	=group(S J T)
	quietly egen tag_SJT	=tag(SJT)
	quietly egen tag_ST	=tag(ST)
	
	*Tau weights
	quietly bys SJT: egen emp_SJT	=total(empl)
	quietly bys ST: egen emp_ST	=total(empl)
	quietly bys JT: egen emp_JT	=total(empl)

	*Share of industry in total local employment
	quietly gen empshare_SJT		=emp_SJT/emp_ST
	
	tempfile originaldata_`ltfpvar'
	quietly save `originaldata_`ltfpvar''
	
*Starting point of loop
local i=1

while(`i'<=`loopnum'){


	use `originaldata_`ltfpvar'', replace
	run "${code}/Covworker.do"
		foreach svar in capT tau {
			tempvar weight
		if("`svar'"=="capT"){
			local tag STR
			gen `weight'=1
			}
			else{
			local tag SJTR
			gen `weight'=empshare_SJT
			}
		quietly cor `svar'_Rb0 `svar'_Rb1  [aw=`weight'] if tag_`tag', cov
		quietly local cov_`svar'b=`r(cov_12)'
		quietly local var_`svar'=`r(Var_2)'
		}

		*Keep taus/capTs for the all sample
		if("`sample'"=="all"){
		quietly keep if tag_STR | tag_SJTR
		quietly keep tau_Rb0 tau_Rb1 capT_Rb0 capT_Rb1 tag_STR tag_SJTR STR SJTR
		quietly gen it=`i'
		if(`i'==1){
			quietly save "${results}/temp/tresh_temp_data_`ltfpvar'.dta", replace
			}
		else{
			quietly append using  "${results}/temp/tresh_temp_data_`ltfpvar'.dta"
			quietly save "${results}/temp/tresh_temp_data_`ltfpvar'.dta", replace
			}
		}
		quietly clear
		quietly set obs 1
		foreach svar in capT tau{
		quietly gen cov_`svar'b=`cov_`svar'b'
		}
		quietly gen tfpvar="`ltfpvar'"
		quietly gen sample="`sample'"
		quietly gen iteration=`i'


if ("`i'"=="1"){
	quietly save "${results}/temp/tresh_results_loop_`sample'_${date}.dta", replace
	}
	else{
	quietly append using "${results}/temp/tresh_results_loop_`sample'_${date}.dta"
	quietly save "${results}/temp/tresh_results_loop_`sample'_${date}.dta", replace
	}
 
local i=`i'+1
}


local ub	=round(.975*`loopnum')
local lb	=max(round(.025*`loopnum'),1)
foreach svar in capT tau{
quietly sort tfpvar cov_`svar'
quietly bys tfpvar: gen ci_ub_cov_`svar'=cov_`svar'[`ub']
quietly bys tfpvar: gen ci_lb_cov_`svar'=cov_`svar'[`lb']
}

foreach svar in capT tau{
	foreach var in  cov{
		quietly gen mean_`var'_`svar' 	=`var'_`svar' 
		}
		}

quietly collapse (first) ci_* (mean) mean_*, by(tfpvar)
quietly gen sample="`sample'"
quietly gen thresh=`thresh'
merge 1:1  thresh sample using "${results}/temp/thresh_results${date}.dta", nogen
save "${results}/temp/thresh_results${date}.dta", replace


